package com.wkh.project.sdk.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.wkh.project.sdk.model.LogMessage;
import com.wkh.project.sdk.push.IPush;
import com.wkh.project.sdk.push.impl.RedisPush;

import java.util.Arrays;

/**
 * @author wangkehua
 * 日志收集
 */
public class MonitorLogAppender<E> extends AppenderBase<E> {
    private String host;
    private Long port;
    private String systemName;
    private String groupId;

    private final IPush redisPush = new RedisPush();
    @Override
    protected void append(E eventObject) {
        //开启推送
        redisPush.open(host, port);
        //获取日志
        if (eventObject instanceof ILoggingEvent event){
            String className = "unknown";
            String methodName = "unknown";
            StackTraceElement[] callerDataArray = event.getCallerData();
            if (callerDataArray != null && callerDataArray.length > 0) {
                StackTraceElement callerData = callerDataArray[0];
                className = callerData.getClassName();
                methodName = callerData.getMethodName();
            }
            //过滤掉非本系统的日志
            if (!className.startsWith(groupId)){
                return;
            }
            //构建日志
            LogMessage logMessage = new LogMessage(systemName, className, methodName, Arrays.asList(event.getFormattedMessage().split(" ")));
            //推送日志
            redisPush.send(logMessage);
        }
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Long getPort() {
        return port;
    }

    public void setPort(Long port) {
        this.port = port;
    }

    public String getSystemName() {
        return systemName;
    }

    public void setSystemName(String systemName) {
        this.systemName = systemName;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }
}
